/*
 * @Author: “ygnnli” “1585923072@qq.com”
 * @Date: 2024-08-02 11:29:28
 * @LastEditors: “ygnnli” “1585923072@qq.com”
 * @LastEditTime: 2024-08-02 20:37:38
 * @FilePath: /110/42/ThreePool.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <queue>
#include <pthread.h>
#include "Thread.hpp"
#include "Log.hpp"
#include "Task.hpp"

using namespace ThreadModule;

const static int gdefaultthreadnum = 3; // 默认线程数量

template <typename T>
class ThreePool
{
private:
    // 加锁
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }
    // 解锁
    void UnlockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }
    // 线程等待
    void ThreadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    // 线程唤醒
    void ThreadWakeup()
    {
        pthread_cond_signal(&_cond);
    }
    // 线程唤醒所有
    void ThreadWakeupAll()
    {
        pthread_cond_broadcast(&_cond);
    }

public:
    ThreePool(int threadnum = gdefaultthreadnum) : _threadnum(threadnum), _waitnum(0), _isrunning(false)
    {
        pthread_mutex_init(&_mutex, NULL); // 创建锁
        pthread_cond_init(&_cond, NULL);   // 创建条件变量
        LOG(INFO, "ThreePool Construct()");
    }

    ~ThreePool()
    {
        pthread_mutex_destroy(&_mutex); // 销毁锁
        pthread_cond_destroy(&_cond);   // 销毁条件变量
    }

    // 启动线程池
    void HandlerTask(std::string name)
    {
        LOG(INFO, "%s is running", name.c_str());
        while (1)
        {
            LockQueue();
            while (_task_queue.empty() && _isrunning) // 如果任务队列为空且线程池正在运行，则线程等待
            {
                _waitnum++;
                ThreadSleep();
                _waitnum--;
            }
            if (_task_queue.empty() && !_isrunning) // 如果任务队列为空且线程池已经停止，则线程退出
            {
                UnlockQueue();
                break;
            }

            T t;
            t = _task_queue.front(); // 获取任务
            _task_queue.pop();       // 弹出任务
            UnlockQueue();
            LOG(DEBUG, "%s get a task", name.c_str());
            t(); // 执行任务
            LOG(DEBUG, "%s handler a task,result is: %s", name.c_str(), t.ResultoString().c_str());
        }
    }

    // 任务进入队列
    bool Enqueue(const T &t)
    {
        bool ret = false;
        LockQueue();
        if (_isrunning == true)
        {
            _task_queue.push(t);
            if (_waitnum > 0)
            {
                ThreadWakeup();
            }
            LOG(DEBUG, "equeue task success");
            ret = true;
        }
        UnlockQueue();
        return ret;
    }

    void Stop() // 停止线程池
    {
        LockQueue();
        _isrunning = false;
        ThreadWakeupAll();
        UnlockQueue();
    }

    void InitThreadPool()
    {
        // 创建多个线程
        for (int num = 0; num < _threadnum; num++)
        {
            std::string name = "thread-" + std::to_string(num + 1);
            //_threads.emplace_back(Print, name);
            // 类的成员方法，也可以成为另一个类的回调方法，方便我们继续类级别的互相调用！
            _threads.emplace_back(std::bind(&ThreePool::HandlerTask, this, std::placeholders::_1), name);
            LOG(INFO, "Init thread %s done", name.c_str());
        }
        _isrunning = true;
    }
    void Start() // 开始
    {
        for (auto &thread : _threads)
        {
            thread.Start();
        }
    }

    void Wait() // 等待
    {
        for (auto &thread : _threads)
        {
            thread.Join();
            LOG(INFO, "%s is quit...", thread.name().c_str());
        }
    }

private:
    int _threadnum;
    std::vector<Thread> _threads;
    std::queue<T> _task_queue;
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    int _waitnum;    // 等待队列中的任务数量
    bool _isrunning; // 线程池是否正在运行
};